package com.wash.framework.utils;

import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class BeanUtils
  implements ApplicationContextAware
{
  private static ApplicationContext APPLICATIONCONTEXT;

  public void setApplicationContext(ApplicationContext applicationContext)
    throws BeansException
  {
    APPLICATIONCONTEXT = applicationContext;
  }

  public static ApplicationContext getApplicationContext()
  {
    return APPLICATIONCONTEXT;
  }

  public static Object getBean(String name)
    throws BeansException
  {
    return APPLICATIONCONTEXT.getBean(name);
  }

  public static Object getBean(String name, Class requiredType)
    throws BeansException
  {
    return APPLICATIONCONTEXT.getBean(name, requiredType);
  }

  public static Object getBean(String name, ApplicationContext ac)
  {
    return ac.getBean(name);
  }

  public static boolean containsBean(String name)
  {
    return APPLICATIONCONTEXT.containsBean(name);
  }

  public static boolean isSingleton(String name)
    throws NoSuchBeanDefinitionException
  {
    return APPLICATIONCONTEXT.isSingleton(name);
  }

  public static Class getType(String name)
    throws NoSuchBeanDefinitionException
  {
    return APPLICATIONCONTEXT.getType(name);
  }

  public static String[] getAliases(String name)
    throws NoSuchBeanDefinitionException
  {
    return APPLICATIONCONTEXT.getAliases(name);
  }

  public static BasicDataSource getDataSource()
    throws BeansException
  {
    return (BasicDataSource)APPLICATIONCONTEXT.getBean("sef.dataSource");
  }

  public static Map<String, Object> convertToMap(Object javabean)
  {
    if (null == javabean) {
      return null;
    }
    Map map = null;
    try {
      map = org.apache.commons.beanutils.BeanUtils.describe(javabean);
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    }
    if (null != map) {
      map.remove("class");
      map = clearNull(map);
    }
    return map;
  }

  public static Map clearNull(Map objectMap)
  {
    Iterator keyIter = objectMap.keySet().iterator();
    while (keyIter.hasNext()) {
      Object key = keyIter.next();
      Object val = objectMap.get(key);
      if (null == val) {
        keyIter.remove();
        objectMap.remove(key);
      }
      else if (((val instanceof String)) && 
        ("".equals(val))) {
        keyIter.remove();
        objectMap.remove(key);
      }
    }

    return objectMap;
  }
}